import Vue from 'vue'
import  Vuex  from  'vuex';

import  axios  from  'axios';

Vue.use(Vuex)

export default new Vuex.Store({
  state:{
     // 8.1 默认从本地取值
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      // 6.4 先中转接收类型字符串
      getSel: "all", // 默认显示全部
      isSel:'all'  //  全部  已完成   未完成
  },
  mutations:{
    setList: function(state,newList){
      state.list=newList
      localStorage.setItem('todoList',JSON.stringify(state.list))
    },
    //  添加数据
    add(state,val){
      state.list.push({id:state.list.length+1,isDone:false,name: val})
      localStorage.setItem('todoList',JSON.stringify(state.list))

      
    },
    del(state,id){
      //  [1,2,3,4,5]  =>3     === [1,2,4,5]   返回的是一个新的数组
      state.list=state.list.filter(item=>{
        return item.id!==id
      })
      localStorage.setItem('todoList',JSON.stringify(state.list))
    },
    clearDoneAll(state){
      
      state.list=state.list.filter(item=>item.isDone===false)
      localStorage.setItem('todoList',JSON.stringify(state.list))
    },

    setIsSel(state,isSel){
      state.isSel=isSel
    }
  },
  actions:{
    async AgetList({commit}){
      //  res.data.data
      const  {data:{data}}=await axios('https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/todos')
      console.log(data,999);
      commit('setList',data)  //  触发mutations中的函数更改list

    }
  },
  getters:{
    count(state){
      //return state.list.filter(item=>item.isDone===false).length  //[1,2,3]
      return state.list.length
    },
    NEWSlist: function(state){

      if(state.isSel==='all'){
        //  全部
        return  state.list

      }else if(state.isSel==='no'){
        //  未完成
        return state.list.filter(item=>item.isDone===false)

      }else{
        //  已完成
        return state.list.filter(item=>item.isDone===true)
      }
    }
  }
})